package AircraftDesignKg.server;

import AircraftDesignKg.entity.DeepSeekRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 流量入口
 */
@Service
public class ServiceImpl {

    private static final Logger log = LogManager.getLogger(ServiceImpl.class);

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Autowired
    private Neo4jCommandService neo4jCommandService;

    @Autowired
    private AiCommandService aiCommandService;

    @Autowired
    private FileService fileService;

    private final RestTemplate restTemplate = new RestTemplate();

    public String callAPI(MultipartFile file) throws Exception {

        long startTime = System.currentTimeMillis();

        String inputContent = fileService.handleFile(file);
        log.info("[info] 文件处理成功");

        DeepSeekRequest request  = aiCommandService.doProcess(inputContent);
        log.info("[info] AI 命令处理成功");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON));
        headers.setBearerAuth(apiKey);
        // 构建请求实体
        HttpEntity<DeepSeekRequest> requestEntity = new HttpEntity<>(request, headers);
        // 发送请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(
                apiUrl,
                requestEntity,
                String.class
        );
        log.info("[info] DeepSeek API 调用成功，响应状态码: {}", response.getStatusCode());
        log.info("[info] DeepSeek API 调用成功，响应内容: {}", response.getBody());

        neo4jCommandService.doProcess(response.getBody());
        log.info("[info] Neo4j 命令处理成功");

        long endTime = System.currentTimeMillis();
        log.info("[info] 主流程处理成功, 总耗时: {}ms", endTime - startTime);

        return "处理成功, 总耗时: " + (endTime - startTime) + "ms";

    }

}